// node 后端服务器
const db = require('./db.js');

const mysql = require('mysql');
const express = require('express');
const app = express();
app.use(express.static('../dist'));
var server = require('http').createServer(app);

var io = require('socket.io')(server);

var conn = mysql.createConnection(db.mysql);
// app.get('/', function(req, res) {
//   res.setHeader("Access-Control-Allow-Origin", "*");
// })
conn.connect();

io.on('connection', function (socket) {
  console.log('a user connected');

  socket.on("disconnect", function () {
    console.log("a user go out");
  });

  socket.on("message", function (obj) {
    let getSql = "SELECT * FROM message";
    let insertSql = "INSERT INTO message (username, password) VALUES ('" + obj.i_user + "','" + obj.i_pass + "');"
    let resultStr, resultjson;
    console.log(obj)
    if(obj.i_user){
    conn.query(insertSql, function (err, result) {
      if (err) {
        console.log(err);
      }
      if (result) {
        console.log(result);
      }
    });
  }
    conn.query(getSql, function (err, result) {
      if (err) {
        console.log(err);
      }
      if (result) {
        resultjson = JSON.stringify(result);
        resultStr = resultjson;
        io.emit("message", resultjson);
      }
    });
    setInterval(function () {
      conn.query(getSql, function (err, result) {
        if (err) {
          console.log(err);
        }
        if (result) {
          resultjson = JSON.stringify(result);
          if (resultStr != resultjson) {
            resultStr = resultjson;
            io.emit("message", resultStr);
          }
        }
      })
    }, 4000);

  });
});

// 监听端口
server.listen(4000);
console.log('success listen at port:4000......');